import { PrismaService } from '@/prisma/prisma.service';
import { Controller, Get } from '@nestjs/common';
import axios from 'axios';
import * as cheerio from 'cheerio';
import { Random, mock } from 'mockjs';
import { SpiderService } from './spider.service';
@Controller('spider')
export class SpiderController {
  constructor(
    private readonly prisma: PrismaService,
    private readonly spiderService: SpiderService,
  ) {}
  @Get()
  async spider() {
    const that = this;
    const requestArray = [];
    const res = await axios.get('https://www.hi2future.com/Mail/showlist2');
    const $ = cheerio.load(res.data);
    for (let i = 2; i < 13; i++) {
      const res = await axios.get(
        `https://www.hi2future.com/Mail/showlist2?page=${i}`,
      );
      const $ = cheerio.load(res.data);
      $('.list-content').each(function (e, element) {
        requestArray.push(that.saveData($(this).html()));
      });
    }
    console.log('----------------------------');
    try {
      await Promise.all(requestArray);
      return '爬取完成';
    } catch (e) {
      return `爬取错误${e}`;
    }
  }
  async saveData(content: string) {
    await this.prisma.postOffice.create({
      data: {
        content,
        emailAddress: Random.email(),
        name: Random.cname(),
        sendDate: new Date(
          `2023-${Math.ceil(Math.random() * 11 + 1)}-${Math.ceil(
            Math.random() * 28 + 1,
          )}`,
        ),
        isPublic: true,
        userId: 1,
      },
    });
  }
}
